package frontend.admin;

import backend.DiseaseItem;
import backend.GeneralDatabase;
import backend.PermissionDenied;
import service.DatabaseManager;

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;

public class DataManagementPanel extends JPanel {
    private final JTable table;
    private final DataTableModel tableModel;
    private final String type; // "user" or "disease"

    public DataManagementPanel(String type) {
        this.type = type;
        setLayout(new BorderLayout());

        // Initialize table model and table
        tableModel = new DataTableModel(type);
        table = new JTable(tableModel);
        table.setRowHeight(30);
        table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));

        // Set up action column
        ActionButtonsRendererEditor buttonsRenderer = new ActionButtonsRendererEditor();
        int actionColumnIndex = type.equals("user") ? 3 : 3; // Last column for both
        table.getColumnModel().getColumn(actionColumnIndex).setCellRenderer(buttonsRenderer);
        table.getColumnModel().getColumn(actionColumnIndex).setCellEditor(buttonsRenderer);

        // Scroll pane
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);

        // Add button
        JButton addButton = createActionButton(type.equals("user") ? "添加用户" : "添加疾病");
        addButton.addActionListener(this::showAddDialog);

        JPanel buttonWrapper = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
        buttonWrapper.add(addButton);
        add(buttonWrapper, BorderLayout.SOUTH);
    }

    private JButton createActionButton(String text) {
        JButton btn = new JButton(text);
        btn.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        btn.setBackground(new Color(70, 130, 180));
        btn.setForeground(Color.WHITE);
        btn.setFocusPainted(false);
        btn.setBorderPainted(false);
        btn.setContentAreaFilled(false);
        btn.setOpaque(true);
        return btn;
    }

    private void showAddDialog(ActionEvent e) {
        SwingUtilities.invokeLater(() -> {
            DataDialog dialog = new DataDialog(
                    (JFrame) SwingUtilities.getWindowAncestor(this),
                    type,
                    null,
                    item -> {
                        if (type.equals("user")) {
                            UserData user = (UserData) item;
                            try {
                                GeneralDatabase db = DatabaseManager.getInstance();
                                String result = db.tryUseradd("admin", user.username, user.password,
                                        Integer.parseInt(user.permission));
                                if ("SUCCESS".equals(result)) {
                                    tableModel.addItem(item);
                                } else {
                                    JOptionPane.showMessageDialog(null, "添加失败: " + result);
                                }
                            } catch (Exception ex) {
                                JOptionPane.showMessageDialog(null, "添加失败: " + ex.getMessage());
                            }
                        } else {
                            DiseaseItem disease = (DiseaseItem) item;
                            try {
                                GeneralDatabase db = DatabaseManager.getInstance();
                                String result = db.tryItemadd("admin", disease);
                                if ("SUCCESS".equals(result)) {
                                    tableModel.addItem(new DiseaseData(disease));
                                } else {
                                    JOptionPane.showMessageDialog(null, "添加失败: " + result);
                                }
                            } catch (Exception ex) {
                                JOptionPane.showMessageDialog(null, "添加失败: " + ex.getMessage());
                            }
                        }
                    }
            );
            dialog.setVisible(true);
        });
    }

    // Data Table Model
    private class DataTableModel extends AbstractTableModel {
        private final String[] columnNames;
        private final List<Object> items = new ArrayList<>();

        public DataTableModel(String type) {
            if (type.equals("user")) {
                columnNames = new String[]{"用户名", "密码", "权限", "操作"};
                loadUsers();
            } else {
                columnNames = new String[]{"疾病名称", "症状", "科室", "操作"};
                loadDiseases();
            }
        }

        private void loadUsers() {
            try {
                GeneralDatabase db = DatabaseManager.getInstance();
                String[][] users = db.getAllUserinfos();
                for (String[] user : users) {
                    items.add(new UserData(user[0], user[1], user[2]));
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "加载用户数据失败: " + e.getMessage());
            }
        }

        private void loadDiseases() {
            try {
                GeneralDatabase db = DatabaseManager.getInstance();
                DiseaseItem[] diseases = db.queryDiseases("");
                for (DiseaseItem disease : diseases) {
                    items.add(new DiseaseData(disease));
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "加载疾病数据失败: " + e.getMessage());
            }
        }

        public void addItem(Object item) {
            items.add(item);
            fireTableRowsInserted(items.size() - 1, items.size() - 1);
        }

        public void updateItem(int rowIndex, Object item) {
            if (rowIndex >= 0 && rowIndex < items.size()) {
                items.set(rowIndex, item);
                fireTableRowsUpdated(rowIndex, rowIndex);
            }
        }

        public void removeItem(int rowIndex) {
            if (rowIndex >= 0 && rowIndex < items.size()) {
                items.remove(rowIndex);
                fireTableRowsDeleted(rowIndex, rowIndex);
            }
        }

        @Override
        public int getRowCount() {
            return items.size();
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

        @Override
        public Object getValueAt(int row, int col) {
            Object item = items.get(row);
            if (type.equals("user")) {
                UserData user = (UserData) item;
                switch (col) {
                    case 0: return user.username;
                    case 1: return user.password;
                    case 2: return user.permission;
                    case 3: return "操作";
                    default: return null;
                }
            } else {
                DiseaseData disease = (DiseaseData) item;
                switch (col) {
                    case 0: return disease.name;
                    case 1: return disease.symptom;
                    case 2: return disease.department;
                    case 3: return "操作";
                    default: return null;
                }
            }
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return column == 3; // Only action column is editable
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return columnIndex == 3 ? JButton.class : Object.class;
        }
    }

    // Data classes
    public static class UserData {
        String username, password, permission;
        UserData(String username, String password, String permission) {
            this.username = username;
            this.password = password;
            this.permission = permission;
        }
    }

    public static class DiseaseData {
        String name, symptom, department;
        DiseaseData(DiseaseItem disease) {
            this.name = disease.Cause();
            this.symptom = disease.Symptom();
            this.department = disease.Department();
        }
    }

    // Action buttons renderer and editor
    private class ActionButtonsRendererEditor extends AbstractCellEditor implements TableCellRenderer, TableCellEditor {
        private final JButton editButton = new JButton("修改");
        private final JButton deleteButton = new JButton("删除");
        private final JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
        private int currentRow = -1;

        public ActionButtonsRendererEditor() {
            setupButton(editButton, new Color(144, 238, 144), Color.WHITE);
            setupButton(deleteButton, new Color(255, 99, 71), Color.WHITE);
            panel.add(editButton);
            panel.add(deleteButton);

            editButton.addActionListener(e -> {
                Object item = tableModel.items.get(currentRow);
                SwingUtilities.invokeLater(() -> {
                    DataDialog dialog = new DataDialog(
                            (JFrame) SwingUtilities.getWindowAncestor(table),
                            type,
                            item,
                            updatedItem -> {
                                try {
                                    GeneralDatabase db = DatabaseManager.getInstance();
                                    if (type.equals("user")) {
                                        // Handle user update
                                        UserData user = (UserData) item;
                                        UserData updatedUser = (UserData) updatedItem;
                                        String result = db.tryUsermod("admin", user.username,
                                                Integer.parseInt(updatedUser.permission));
                                        if ("SUCCESS".equals(result)) {
                                            tableModel.updateItem(currentRow, updatedItem);
                                        } else {
                                            JOptionPane.showMessageDialog(null, "更新失败: " + result);
                                        }
                                    } else {
                                        // Handle disease update
                                        DiseaseData disease = (DiseaseData) item;
                                        DiseaseItem updatedDisease = (DiseaseItem) updatedItem;

                                        DiseaseItem oldItem = new DiseaseItem()
                                                .Cause(disease.name)
                                                .Symptom(disease.symptom)
                                                .Department(disease.department);

                                        String delResult = db.tryItemdel("admin", oldItem);
                                        if ("SUCCESS".equals(delResult)) {
                                            String addResult = db.tryItemadd("admin", updatedDisease);
                                            if ("SUCCESS".equals(addResult)) {
                                                tableModel.updateItem(currentRow, new DiseaseData(updatedDisease));
                                            } else {
                                                JOptionPane.showMessageDialog(null, "更新失败: " + addResult);
                                                // Rollback
                                                db.tryItemadd("admin", oldItem);
                                            }
                                        } else {
                                            JOptionPane.showMessageDialog(null, "更新失败: " + delResult);
                                        }
                                    }
                                } catch (Exception ex) {
                                    JOptionPane.showMessageDialog(null, "操作失败: " + ex.getMessage());
                                }
                            }
                    );
                    dialog.setVisible(true);
                });
            });

            deleteButton.addActionListener(e -> {
                if (JOptionPane.showConfirmDialog(null, "确定删除该" +
                        (type.equals("user") ? "用户" : "疾病") + "？") == JOptionPane.OK_OPTION) {
                    try {
                        GeneralDatabase db = DatabaseManager.getInstance();
                        Object item = tableModel.items.get(currentRow);
                        String result;

                        if (type.equals("user")) {
                            UserData user = (UserData) item;
                            result = db.tryUserdel("admin", user.username);
                        } else {
                            DiseaseData disease = (DiseaseData) item;
                            DiseaseItem diseaseItem = new DiseaseItem()
                                    .Cause(disease.name)
                                    .Symptom(disease.symptom)
                                    .Department(disease.department);
                            result = db.tryItemdel("admin", diseaseItem);
                        }

                        if ("SUCCESS".equals(result)) {
                            tableModel.removeItem(currentRow);
                        } else {
                            JOptionPane.showMessageDialog(null, "删除失败: " + result);
                        }
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, "删除失败: " + ex.getMessage());
                    }
                }
                fireEditingStopped();
            });
        }

        private void setupButton(JButton button, Color bgColor, Color fgColor) {
            button.setBackground(bgColor);
            button.setForeground(fgColor);
            button.setFocusPainted(false);
            button.setBorderPainted(false);
            button.setContentAreaFilled(false);
            button.setOpaque(true);
            button.setRolloverEnabled(false);
            button.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus, int row, int column) {
            currentRow = row;
            editButton.setBackground(new Color(144, 238, 144));
            deleteButton.setBackground(new Color(255, 99, 71));
            panel.setBackground(table.getBackground());
            return panel;
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value,
                                                     boolean isSelected, int row, int column) {
            currentRow = row;
            editButton.setBackground(new Color(144, 238, 144));
            deleteButton.setBackground(new Color(255, 99, 71));
            panel.setBackground(table.getBackground());
            return panel;
        }

        @Override
        public Object getCellEditorValue() {
            return null;
        }
    }
}
